package com.zhiqianbao.utils;

import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hp on 2017/7/25.
 */
public class WifiInfoUtil {
    WifiManager wifiManager;
    public WifiInfoUtil(WifiManager wifiManager){
        this.wifiManager=wifiManager;
    }

    public List getWifiList(){
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        List listwife = new ArrayList<>();
        Map<Object, Object> map = new HashMap<>();
        String bssid = wifiInfo.getBSSID();
        String ssid = wifiInfo.getSSID();
        String macAddress = getDeviceMacAddress();
        map.put("bssid",bssid);
        map.put("name",ssid);
        map.put("mac",macAddress);
        listwife.add(map);
        return  listwife;
    }
    // Android 6.0之前的版本可以用的方法（模拟器可以使用）
    private String getMacAddrOld(){
        String macString = "";
        if (wifiManager != null)
        {
            if (wifiManager.getConnectionInfo() != null)
            {
                if (wifiManager.getConnectionInfo().getMacAddress() != null)
                {
                    macString = wifiManager.getConnectionInfo().getMacAddress();
                }
            }
        }
        return macString;
    }

    /**
     * 可以获取Android6.0系统的wifi Mac 地址。
     * 但是这个方法，却获取不到模拟器的地址，或者是获取到的和上面的方法不同，而且不准确。
     * @return
     */
    public String getMacAddr() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:",b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
        }
        return "02:00:00:00:00:00";
    }

    /**
     * 获取不同安卓系统版本对应的wifi的mac地址
     * @return
     */
    public String getDeviceMacAddress()
    {
        String addr = getMacAddrOld();
        if(addr.equals("02:00:00:00:00:00"))
        {
            addr = getMacAddr();
        }
        return addr;
    }
}
